/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;

import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.*;

/**
 * An {@link ExecutorService} that executes each submitted task using
 * one of possibly several pooled threads, normally configured
 * using {@link Executors} factory methods.
 *
 * <p>Thread pools address two different problems: they usually
 * provide improved performance when executing large numbers of
 * asynchronous tasks, due to reduced per-task invocation overhead,
 * and they provide a means of bounding and managing the resources,
 * including threads, consumed when executing a collection of tasks.
 * Each {@code ThreadPoolExecutor} also maintains some basic
 * statistics, such as the number of completed tasks.
 *
 * <p>To be useful across a wide range of contexts, this class
 * provides many adjustable parameters and extensibility
 * hooks. However, programmers are urged to use the more convenient
 * {@link Executors} factory methods {@link
 * Executors#newCachedThreadPool} (unbounded thread pool, with
 * automatic thread reclamation), {@link Executors#newFixedThreadPool}
 * (fixed size thread pool) and {@link
 * Executors#newSingleThreadExecutor} (single background thread), that
 * preconfigure settings for the most common usage
 * scenarios. Otherwise, use the following guide when manually
 * configuring and tuning this class:
 *
 * <dl>
 *
 * <dt>Core and maximum pool sizes</dt>
 *
 * <dd>A {@code ThreadPoolExecutor} will automatically adjust the
 * pool size (see {@link #getPoolSize})
 * according to the bounds set by
 * corePoolSize (see {@link #getCorePoolSize}) and
 * maximumPoolSize (see {@link #getMaximumPoolSize}).
 *
 * When a new task is submitted in method {@link #execute(Runnable)},
 * and fewer than corePoolSize threads are running, a new thread is
 * created to handle the request, even if other worker threads are
 * idle.  If there are more than corePoolSize but less than
 * maximumPoolSize threads running, a new thread will be created only
 * if the queue is full.  By setting corePoolSize and maximumPoolSize
 * the same, you create a fixed-size thread pool. By setting
 * maximumPoolSize to an essentially unbounded value such as {@code
 * Integer.MAX_VALUE}, you allow the pool to accommodate an arbitrary
 * number of concurrent tasks. Most typically, core and maximum pool
 * sizes are set only upon construction, but they may also be changed
 * dynamically using {@link #setCorePoolSize} and {@link
 * #setMaximumPoolSize}. </dd>
 *
 * <dt>On-demand construction</dt>
 *
 * <dd>By default, even core threads are initially created and
 * started only when new tasks arrive, but this can be overridden
 * dynamically using method {@link #prestartCoreThread} or {@link
 * #prestartAllCoreThreads}.  You probably want to prestart threads if
 * you construct the pool with a non-empty queue. </dd>
 *
 * <dt>Creating new threads</dt>
 *
 * <dd>New threads are created using a {@link ThreadFactory}.  If not
 * otherwise specified, a {@link Executors#defaultThreadFactory} is
 * used, that creates threads to all be in the same {@link
 * ThreadGroup} and with the same {@code NORM_PRIORITY} priority and
 * non-daemon status. By supplying a different ThreadFactory, you can
 * alter the thread's name, thread group, priority, daemon status,
 * etc. If a {@code ThreadFactory} fails to create a thread when asked
 * by returning null from {@code newThread}, the executor will
 * continue, but might not be able to execute any tasks. Threads
 * should possess the "modifyThread" {@code RuntimePermission}. If
 * worker threads or other threads using the pool do not possess this
 * permission, service may be degraded: configuration changes may not
 * take effect in a timely manner, and a shutdown pool may remain in a
 * state in which termination is possible but not completed.</dd>
 *
 * <dt>Keep-alive times</dt>
 *
 * <dd>If the pool currently has more than corePoolSize threads,
 * excess threads will be terminated if they have been idle for more
 * than the keepAliveTime (see {@link #getKeepAliveTime(TimeUnit)}).
 * This provides a means of reducing resource consumption when the
 * pool is not being actively used. If the pool becomes more active
 * later, new threads will be constructed. This parameter can also be
 * changed dynamically using method {@link #setKeepAliveTime(long,
 * TimeUnit)}.  Using a value of {@code Long.MAX_VALUE} {@link
 * TimeUnit#NANOSECONDS} effectively disables idle threads from ever
 * terminating prior to shut down. By default, the keep-alive policy
 * applies only when there are more than corePoolSize threads. But
 * method {@link #allowCoreThreadTimeOut(boolean)} can be used to
 * apply this time-out policy to core threads as well, so long as the
 * keepAliveTime value is non-zero. </dd>
 *
 * <dt>Queuing</dt>
 *
 * <dd>Any {@link BlockingQueue} may be used to transfer and hold
 * submitted tasks.  The use of this queue interacts with pool sizing:
 *
 * <ul>
 *
 * <li> If fewer than corePoolSize threads are running, the Executor
 * always prefers adding a new thread
 * rather than queuing.</li>
 *
 * <li> If corePoolSize or more threads are running, the Executor
 * always prefers queuing a request rather than adding a new
 * thread.</li>
 *
 * <li> If a request cannot be queued, a new thread is created unless
 * this would exceed maximumPoolSize, in which case, the task will be
 * rejected.</li>
 *
 * </ul>
 *
 * There are three general strategies for queuing:
 * <ol>
 *
 * <li> <em> Direct handoffs.</em> A good default choice for a work
 * queue is a {@link SynchronousQueue} that hands off tasks to threads
 * without otherwise holding them. Here, an attempt to queue a task
 * will fail if no threads are immediately available to run it, so a
 * new thread will be constructed. This policy avoids lockups when
 * handling sets of requests that might have internal dependencies.
 * Direct handoffs generally require unbounded maximumPoolSizes to
 * avoid rejection of new submitted tasks. This in turn admits the
 * possibility of unbounded thread growth when commands continue to
 * arrive on average faster than they can be processed.  </li>
 *
 * <li><em> Unbounded queues.</em> Using an unbounded queue (for
 * example a {@link LinkedBlockingQueue} without a predefined
 * capacity) will cause new tasks to wait in the queue when all
 * corePoolSize threads are busy. Thus, no more than corePoolSize
 * threads will ever be created. (And the value of the maximumPoolSize
 * therefore doesn't have any effect.)  This may be appropriate when
 * each task is completely independent of others, so tasks cannot
 * affect each others execution; for example, in a web page server.
 * While this style of queuing can be useful in smoothing out
 * transient bursts of requests, it admits the possibility of
 * unbounded work queue growth when commands continue to arrive on
 * average faster than they can be processed.  </li>
 *
 * <li><em>Bounded queues.</em> A bounded queue (for example, an
 * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
 * used with finite maximumPoolSizes, but can be more difficult to
 * tune and control.  Queue sizes and maximum pool sizes may be traded
 * off for each other: Using large queues and small pools minimizes
 * CPU usage, OS resources, and context-switching overhead, but can
 * lead to artificially low throughput.  If tasks frequently block (for
 * example if they are I/O bound), a system may be able to schedule
 * time for more threads than you otherwise allow. Use of small queues
 * generally requires larger pool sizes, which keeps CPUs busier but
 * may encounter unacceptable scheduling overhead, which also
 * decreases throughput.  </li>
 *
 * </ol>
 *
 * </dd>
 *
 * <dt>Rejected tasks</dt>
 *
 * <dd>New tasks submitted in method {@link #execute(Runnable)} will be
 * <em>rejected</em> when the Executor has been shut down, and also when
 * the Executor uses finite bounds for both maximum threads and work queue
 * capacity, and is saturated.  In either case, the {@code execute} method
 * invokes the {@link
 * RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor)}
 * method of its {@link RejectedExecutionHandler}.  Four predefined handler
 * policies are provided:
 *
 * <ol>
 *
 * <li> In the default {@link ThreadPoolExecutor.AbortPolicy}, the
 * handler throws a runtime {@link RejectedExecutionException} upon
 * rejection. </li>
 *
 * <li> In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread
 * that invokes {@code execute} itself runs the task. This provides a
 * simple feedback control mechanism that will slow down the rate that
 * new tasks are submitted. </li>
 *
 * <li> In {@link ThreadPoolExecutor.DiscardPolicy}, a task that
 * cannot be executed is simply dropped.  </li>
 *
 * <li>In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the
 * executor is not shut down, the task at the head of the work queue
 * is dropped, and then execution is retried (which can fail again,
 * causing this to be repeated.) </li>
 *
 * </ol>
 *
 * It is possible to define and use other kinds of {@link
 * RejectedExecutionHandler} classes. Doing so requires some care
 * especially when policies are designed to work only under particular
 * capacity or queuing policies. </dd>
 *
 * <dt>Hook methods</dt>
 *
 * <dd>This class provides {@code protected} overridable
 * {@link #beforeExecute(Thread, Runnable)} and
 * {@link #afterExecute(Runnable, Throwable)} methods that are called
 * before and after execution of each task.  These can be used to
 * manipulate the execution environment; for example, reinitializing
 * ThreadLocals, gathering statistics, or adding log entries.
 * Additionally, method {@link #terminated} can be overridden to perform
 * any special processing that needs to be done once the Executor has
 * fully terminated.
 *
 * <p>If hook or callback methods throw exceptions, internal worker
 * threads may in turn fail and abruptly terminate.</dd>
 *
 * <dt>Queue maintenance</dt>
 *
 * <dd>Method {@link #getQueue()} allows access to the work queue
 * for purposes of monitoring and debugging.  Use of this method for
 * any other purpose is strongly discouraged.  Two supplied methods,
 * {@link #remove(Runnable)} and {@link #purge} are available to
 * assist in storage reclamation when large numbers of queued tasks
 * become cancelled.</dd>
 *
 * <dt>Finalization</dt>
 *
 * <dd>A pool that is no longer referenced in a program <em>AND</em>
 * has no remaining threads will be {@code shutdown} automatically. If
 * you would like to ensure that unreferenced pools are reclaimed even
 * if users forget to call {@link #shutdown}, then you must arrange
 * that unused threads eventually die, by setting appropriate
 * keep-alive times, using a lower bound of zero core threads and/or
 * setting {@link #allowCoreThreadTimeOut(boolean)}.  </dd>
 *
 * </dl>
 *
 * <p><b>Extension example</b>. Most extensions of this class
 * override one or more of the protected hook methods. For example,
 * here is a subclass that adds a simple pause/resume feature:
 *
 *  <pre> {@code
 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
 *   private boolean isPaused;
 *   private ReentrantLock pauseLock = new ReentrantLock();
 *   private Condition unpaused = pauseLock.newCondition();
 *
 *   public PausableThreadPoolExecutor(...) { super(...); }
 *
 *   protected void beforeExecute(Thread t, Runnable r) {
 *     super.beforeExecute(t, r);
 *     pauseLock.lock();
 *     try {
 *       while (isPaused) unpaused.await();
 *     } catch (InterruptedException ie) {
 *       t.interrupt();
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 *
 *   public void pause() {
 *     pauseLock.lock();
 *     try {
 *       isPaused = true;
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 *
 *   public void resume() {
 *     pauseLock.lock();
 *     try {
 *       isPaused = false;
 *       unpaused.signalAll();
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 * }}</pre>
 *
 * @since 1.5
 * @author Doug Lea
 */
public class ThreadPoolExecutor extends AbstractExecutorService {
    /**
     * 主要的线程池控制状态ctl是一个原子整数，用于组合两个概念字段：
     *   ctl：高三位表示线程池运行状态，低29位表示线程池线程运行数量
     *   workerCount，表示有效线程数
     *   runState，表示运行状态、关闭状态等
     *
     * 为了将它们打包成一个整数，我们将workerCount限制为（2^29）-1（约5亿）个线程，
     * 而不是（2^31）-1（20亿）个线程，因为后者可以表示的线程数更多。如果将来出现问题，
     * 可以将变量更改为AtomicLong，并相应调整下面的移位和掩码常量。但在需要之前，使用整数的代码更快且更简单。
     *
     * workerCount是已被允许启动但不允许停止的工作线程数。该值可能短暂地与实际的活动线程数不同，
     * 例如当ThreadFactory无法在被请求时创建线程，以及退出的线程在终止前仍在执行簿记。用户可见的池大小报告为工作线程集的当前大小。
     *
     * runState提供主要的生命周期控制，它有以下值
     *   RUNNING:   接受新任务并处理排队的任务
     *   SHUTDOWN:  不接受新任务，但处理排队的任务
     *   STOP:      不接受新任务，不处理排队的任务，并中断正在进行的任务
     *   TIDYING:   所有任务已终止，workerCount为零，正在过渡到TIDYING状态的线程将运行terminated()钩子方法
     *   TERMINATED: terminated()已完成
     *
     * 这些值之间的数字顺序很重要，以允许有序的比较。runState会随时间单调增加，但不一定会经历每个状态。转换如下：
     *
     *          /--SHUTDOWN--\
     *         /              \
     *  RUNNING               TIDYING -- TERMINATED
     *         \             /
     *          \-- STOP  --/
     *
     * RUNNING -> SHUTDOWN
     *    在调用shutdown()时，可能隐式在finalize()中调用。
     * (RUNNING or SHUTDOWN) -> STOP
     *    在调用shutdownNow()时。
     * SHUTDOWN -> TIDYING
     *    当队列和线程池都为空时。
     * STOP -> TIDYING
     *    当线程池为空时。
     * TIDYING -> TERMINATED
     *    当terminated()钩子方法完成时。
     *
     * 在awaitTermination()中等待的线程将在状态达到TERMINATED时返回。
     *
     * 检测从SHUTDOWN到TIDYING的过渡不像你期望的那么简单，因为在SHUTDOWN状态下，队列可能在非空和空之间切换，
     * 反之亦然，但只有在看到队列为空后，我们才能终止，前提是我们看到workerCount为0（有时需要重新检查，参见下文）。
     */
    //ctlOf(RUNNING, 0)后还是RUNNING  11100000000000000000000000000000
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    private static final int COUNT_BITS = Integer.SIZE - 3;//29
    //536870911做多5亿多个
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;//00011111111111111111111111111111

    // 运行状态（runState）存储在高位比特中  高3位。
    private static final int RUNNING    = -1 << COUNT_BITS;//11100000000000000000000000000000
    private static final int SHUTDOWN   =  0 << COUNT_BITS;//00000000000000000000000000000000
    private static final int STOP       =  1 << COUNT_BITS;//00100000000000000000000000000000
    private static final int TIDYING    =  2 << COUNT_BITS;//01000000000000000000000000000000
    private static final int TERMINATED =  3 << COUNT_BITS;//01100000000000000000000000000000

    // 获取线程池当前的运行状态（～：按位取反，即0变成1，1变成0。）
    private static int runStateOf(int c)     { return c & ~CAPACITY; }//~CAPACITY的二进制为 11100000000000000000000000000000
    // 获取线程池当前运行的线程数量
    private static int workerCountOf(int c)  { return c & CAPACITY; }
    // 通过线程池状态和运行的线程数量获取ctl
    private static int ctlOf(int rs, int wc) { return rs | wc; }

    //这些位字段访问器不需要解包 ctl（控制字段）。这些访问器依赖于位布局和 workerCount 永远不会为负数。

    private static boolean runStateLessThan(int c, int s) {
        return c < s;
    }

    private static boolean runStateAtLeast(int c, int s) {
        return c >= s;
    }

    private static boolean isRunning(int c) {
        return c < SHUTDOWN;
    }

    /**
     * 尝试使用 CAS（Compare and Swap）原子操作来增加 ctl 的 workerCount 字段。
     */
    private boolean compareAndIncrementWorkerCount(int expect) {
        return ctl.compareAndSet(expect, expect + 1);
    }

    /**
     * 尝试使用 CAS（Compare and Swap）原子操作来减少 ctl 的 workerCount 字段。
     */
    private boolean compareAndDecrementWorkerCount(int expect) {
        return ctl.compareAndSet(expect, expect - 1);
    }

    /**
     * 减少 ctl 的 workerCount 字段。这仅在线程突然终止时调用（参见 processWorkerExit）。其他减少操作在 getTask 中执行。
     */
    private void decrementWorkerCount() {
        do {} while (! compareAndDecrementWorkerCount(ctl.get()));
    }

    /**
     * 用于保存任务并交给工作线程处理的队列。我们不要求 workQueue.poll() 返回 null 就意味着 workQueue.isEmpty()，
     * 所以我们完全依赖 isEmpty 来判断队列是否为空（例如在决定是否从 SHUTDOWN 状态转换为 TIDYING 状态时必须这样做）。
     * 这适用于特殊用途的队列，例如 DelayQueue，其中即使在延迟过期后可能返回非 null，但允许 poll() 返回 null。
     */
    private final BlockingQueue<Runnable> workQueue;

    /**
     * 在访问 workers 集合和相关的记录时持有的锁。虽然我们可以使用某种并发集合，但事实证明使用锁通常更可取。
     * 其中的原因之一是，这样可以序列化 interruptIdleWorkers 操作，避免不必要的中断风暴，尤其是在关闭过程中。
     * 否则，正在退出的线程将与尚未中断的线程并发地进行中断。这还简化了一些相关的统计信息记录，
     * 例如 largestPoolSize 等。在关闭和 shutdownNow 期间，我们还持有 mainLock 锁，以确保 workers 集合在单独检查中断权限和实际中断时保持稳定。
     */
    private final ReentrantLock mainLock = new ReentrantLock();

    /**
     * 线程池中所有线程的set集合，仅当持有main锁时才能访问该集合。
     */
    private final HashSet<Worker> workers = new HashSet<Worker>();

    /**
     * 等待条件用于支持 awaitTermination 方法。
     */
    private final Condition termination = mainLock.newCondition();

    /**
     * 追踪线程池曾达到的最大的池数量
     */
    private int largestPoolSize;

    /**
     * 已完成任务的计数器。仅在工作线程终止时进行更新。仅在主锁（mainLock）下访问。
     */
    private long completedTaskCount;

    /*
     * All user control parameters are declared as volatiles so that
     * ongoing actions are based on freshest values, but without need
     * for locking, since no internal invariants depend on them
     * changing synchronously with respect to other actions.
     */

    /**
     * 用于创建新线程的工厂。所有线程都是使用此工厂创建的（通过 addWorker 方法）。
     * 所有调用者必须准备处理 addWorker 可能失败的情况，这可能反映出系统或用户的策略限制线程数量。
     * 即使它不被视为错误，无法创建线程可能会导致新任务被拒绝或现有任务在队列中停滞不前。
     *
     * 我们进一步保持了线程池的不变条件，即使在创建线程时出现 OutOfMemoryError 等错误的情况下也是如此。
     * 由于在 Thread.start 中需要分配本地栈，这样的错误是相当常见的，用户希望执行清理线程池以进行清理。
     * 清理代码很可能有足够的可用内存来完成，而不会再次遇到 OutOfMemoryError。
     */
    private volatile ThreadFactory threadFactory;

    /**
     * 在执行任务时，当线程池饱和或处于关闭状态时调用的处理程序。
     */
    private volatile RejectedExecutionHandler handler;

    /**
     * 空闲线程等待工作的超时时间，以纳秒为单位。
     * 当存在超过核心线程池大小（corePoolSize）的线程或允许核心线程超时（allowCoreThreadTimeOut）时，线程使用此超时时间。否则，它们将永远等待新的工作。
     */
    private volatile long keepAliveTime;

    /**
     * 如果为 false（默认值），核心线程即使空闲也会保持活动状态。如果为 true，核心线程会使用 keepAliveTime 来设置等待任务的超时时间。
     */
    private volatile boolean allowCoreThreadTimeOut;

    /**
     * 核心线程池大小是保持活动状态的最小工作线程数（不允许它们超时等等），除非设置了 allowCoreThreadTimeOut，否则最小值为零。
     */
    private volatile int corePoolSize;

    /**
     * 线程池的最大线程数。请注意，实际的最大线程数在内部受到 CAPACITY 的限制。
     */
    private volatile int maximumPoolSize;

    /**
     * 默认的拒绝策略 抛出拒绝异常
     */
    private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();

    /**
     * Permission required for callers of shutdown and shutdownNow.
     * We additionally require (see checkShutdownAccess) that callers
     * have permission to actually interrupt threads in the worker set
     * (as governed by Thread.interrupt, which relies on
     * ThreadGroup.checkAccess, which in turn relies on
     * SecurityManager.checkAccess). Shutdowns are attempted only if
     * these checks pass.
     *
     * All actual invocations of Thread.interrupt (see
     * interruptIdleWorkers and interruptWorkers) ignore
     * SecurityExceptions, meaning that the attempted interrupts
     * silently fail. In the case of shutdown, they should not fail
     * unless the SecurityManager has inconsistent policies, sometimes
     * allowing access to a thread and sometimes not. In such cases,
     * failure to actually interrupt threads may disable or delay full
     * termination. Other uses of interruptIdleWorkers are advisory,
     * and failure to actually interrupt will merely delay response to
     * configuration changes so is not handled exceptionally.
     */
    private static final RuntimePermission shutdownPerm =
        new RuntimePermission("modifyThread");

    /* The context to be used when executing the finalizer, or null. */
    private final AccessControlContext acc;

    /**
     * Worker 类主要用于维护运行任务的线程的中断控制状态，以及其他次要的记录。
     * 这个类巧妙地扩展了 AbstractQueuedSynchronizer，以简化每个任务执行周围的获取和释放锁的过程。
     * 这样可以防止意图唤醒等待任务的工作线程的中断，而中断正在运行的任务。
     * 我们实现了一个简单的非可重入互斥锁，而不是使用 ReentrantLock，因为我们不希望工作任务能够在调用像 setCorePoolSize 这样的池控制方法时重新获取锁。
     * 另外，为了在线程实际开始运行任务之前抑制中断，我们将锁的状态初始化为负值，并在启动时清除它（在 runWorker 方法中）。
     */
    private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
        /**
         * This class will never be serialized, but we provide a
         * serialVersionUID to suppress a javac warning.
         */
        private static final long serialVersionUID = 6138294804551838833L;

        /** 该工作线程正在运行的线程。如果工厂创建失败，则为 null。 */
        final Thread thread;
        /** =要运行的初始任务。可能为空。*/
        Runnable firstTask;
        /** 当前worker已经完成了多少次任务。*/
        volatile long completedTasks;

        /**
         * Creates with given first task and thread from ThreadFactory.
         * @param firstTask the first task (null if none)
         */
        Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker 禁止中断直到 runWorker执行
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

        /** 将主运行循环委托给外部运行工作器  */
        public void run() {
            runWorker(this);
        }

        // Lock methods
        //
        // The value 0 represents the unlocked state.
        // The value 1 represents the locked state.

        protected boolean isHeldExclusively() {
            return getState() != 0;
        }

        protected boolean tryAcquire(int unused) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        protected boolean tryRelease(int unused) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        public void lock()        { acquire(1); }
        public boolean tryLock()  { return tryAcquire(1); }
        public void unlock()      { release(1); }
        public boolean isLocked() { return isHeldExclusively(); }

        void interruptIfStarted() {
            Thread t;
            if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
                try {
                    t.interrupt();
                } catch (SecurityException ignore) {
                }
            }
        }
    }

    /*
     * Methods for setting control state
     */

    /**
     * 将 runState 转换为给定的目标状态，如果已经至少达到给定的目标状态，则保持不变。
     *
     * @param targetState the desired state, either SHUTDOWN or STOP
     *        (but not TIDYING or TERMINATED -- use tryTerminate for that)
     */
    private void advanceRunState(int targetState) {
        for (;;) {
            int c = ctl.get();
            if (runStateAtLeast(c, targetState) || ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
                break;
        }
    }

    /**
     * 如果满足以下条件之一，将转换为 TERMINATED 状态：
     * SHUTDOWN 并且线程池和任务队列都为空。
     * STOP 并且线程池为空。
     * 如果满足终止的条件，但 workerCount 不为零，则中断一个空闲的工作线程以确保关闭信号传播。
     * 在可能导致终止的任何操作之后，必须调用此方法 - 减少 worker 计数或在关闭期间从队列中移除任务。
     * 该方法是非私有的，以便允许 ScheduledThreadPoolExecutor 访问。
     */
    final void tryTerminate() {
        for (;;) {
            int c = ctl.get();
            //线程池处于-->运行中  或  TIDYING、TERMINATED  或  SHUTDOWN单队列不为空
            if (isRunning(c) || runStateAtLeast(c, TIDYING) || (runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
                return;
            //SHUTDOWN且对列为空 或者 STOP
            if (workerCountOf(c) != 0) { // Eligible to terminate
                //中断空闲线程
                interruptIdleWorkers(ONLY_ONE);
                return;
            }

            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
                    try {
                        terminated();
                    } finally {
                        ctl.set(ctlOf(TERMINATED, 0));
                        termination.signalAll();
                    }
                    return;
                }
            } finally {
                mainLock.unlock();
            }
            // else retry on failed CAS
        }
    }

    /*
     * Methods for controlling interrupts to worker threads.
     */

    /**
     * If there is a security manager, makes sure caller has
     * permission to shut down threads in general (see shutdownPerm).
     * If this passes, additionally makes sure the caller is allowed
     * to interrupt each worker thread. This might not be true even if
     * first check passed, if the SecurityManager treats some threads
     * specially.
     */
    private void checkShutdownAccess() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkPermission(shutdownPerm);
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                for (Worker w : workers)
                    security.checkAccess(w.thread);
            } finally {
                mainLock.unlock();
            }
        }
    }

    /**
     * 中断所有线程，即使它们处于活动状态。忽略 SecurityExceptions（在这种情况下，一些线程可能保持未中断状态）。
     */
    private void interruptWorkers() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers)
                w.interruptIfStarted();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 中断可能正在等待任务的线程（通过未锁定状态来指示），以便它们可以检查终止或配置更改。忽略 SecurityExceptions（在这种情况下，一些线程可能保持未中断状态）。
     * onlyOne 如果为 true，则最多中断一个工作线程。仅在终止否则已启用但仍有其他工作线程时，
     * 从 tryTerminate 中调用此方法。在这种情况下，最多中断一个等待的工作线程以传播关闭信号，
     * 以防当前所有线程都处于等待状态。中断任意一个线程可以确保自从关闭开始以来新到达的工作线程最终也会退出。
     * 为了确保最终终止，仅中断一个空闲的工作线程就足够了，但是 shutdown() 中断所有空闲的工作线程，以便冗余的工作线程能够迅速退出，
     * 而不必等待一个滞后的任务完成。
     */
    private void interruptIdleWorkers(boolean onlyOne) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers) {
                Thread t = w.thread;
                if (!t.isInterrupted() && w.tryLock()) {
                    try {
                        //发出中断信号
                        t.interrupt();
                    } catch (SecurityException ignore) {
                    } finally {
                        w.unlock();
                    }
                }
                if (onlyOne)
                    break;
            }
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 用于中断空闲工作线程的常见形式，避免需要记住布尔参数的含义。
     */
    private void interruptIdleWorkers() {
        interruptIdleWorkers(false);
    }

    private static final boolean ONLY_ONE = true;

    /*
     * Misc utilities, most of which are also exported to
     * ScheduledThreadPoolExecutor
     */

    /**
     * 调用给定命令的拒绝执行处理程序。对 ScheduledThreadPoolExecutor 使用的包内可见。
     */
    final void reject(Runnable command) {
        handler.rejectedExecution(command, this);
    }

    /**
     * 在调用 shutdown 后执行运行状态转换后的任何进一步清理工作。这里是一个空操作，但 ScheduledThreadPoolExecutor 在取消延迟任务时会使用它。
     */
    void onShutdown() {
    }

    /**
     * State check needed by ScheduledThreadPoolExecutor to
     * enable running tasks during shutdown.
     *
     * @param shutdownOK true if should return true if SHUTDOWN
     */
    final boolean isRunningOrShutdown(boolean shutdownOK) {
        int rs = runStateOf(ctl.get());
        return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
    }

    /**
     * 将任务队列中的任务转移到一个新的列表中，通常使用 drainTo 方法。
     * 但如果队列是 DelayQueue 或者是其他 poll 或 drainTo 方法可能无法成功移除某些元素的队列，那么会逐个删除它们。
     */
    private List<Runnable> drainQueue() {
        BlockingQueue<Runnable> q = workQueue;
        ArrayList<Runnable> taskList = new ArrayList<Runnable>();
        q.drainTo(taskList);
        if (!q.isEmpty()) {
            for (Runnable r : q.toArray(new Runnable[0])) {
                if (q.remove(r))
                    taskList.add(r);
            }
        }
        return taskList;
    }

    /*
     * Methods for creating, running and cleaning up after workers
     */

    /**
     * 检查是否可以根据当前池状态和给定的边界（核心池大小或最大池大小）添加新的工作线程。如果可以，工作线程计数将相应调整，并且如果可能，
     * 将创建并启动一个新的工作线程，其中第一个任务为 firstTask。如果线程池已停止或有资格关闭，则此方法返回 false。
     * 如果线程工厂在被请求时无法创建线程，则也返回 false。如果线程创建失败，可能是由于线程工厂返回 null 或由于异常（通常是 Thread.start()
     * 中的 OutOfMemoryError），我们会进行干净的回滚。
     *
     * @param firstTask
     * 新线程应首先运行的任务（如果没有，则为 null）。当线程数少于核心池大小时（在方法 execute() 中），我们创建具有初始第一个任务的工作线程，
     * 以避免排队，或者当队列已满时（在这种情况下，我们必须绕过队列）。最初空闲的线程通常是通过 prestartCoreThread 或用于替换其他正在退出的工作线程创建的。
     *
     * @param core 如果为 true，则使用核心池大小作为边界；否则使用最大池大小。（在此处使用布尔值指示符而不是值，以确保在检查其他池状态后读取最新值）。
     * @return true if successful
     */
    private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            // 仅在必要时检查队列是否为空
            if (rs >= SHUTDOWN &&
                    //当rs为 STOP、TIDYING、TERMINATED则直接返回false
                    //当rs为 SHUTDOWN,如果firstTask为空并且队列中有任务，此时允许增加工作线程来执行任务(理解为：让这个线程来取队列中的任务去执行)
                ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
                if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                //使用CAS的方法给ctl的worker的数量加1 成功则跳出最外层循环
                if (compareAndIncrementWorkerCount(c))
                    //添加数量成功，可以真正去创建worker了
                    break retry;
                c = ctl.get();  // Re-read ctl
                //如果不成功的原因是状态变了 就重新进行外层循环
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        // worker是否开始执行，也就是是否执行：t.start();
        boolean workerStarted = false;
        // worker是否被加到workers里（workers，HashSet）
        boolean workerAdded = false;
        Worker w = null;
        try {
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                // 加锁目的是为了保证下面的workers.add(worker)方法在多线程操作时候是线程安全的。
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // Recheck while holding lock.获取到锁后重新检查线程池状态
                    // Back out on ThreadFactory failure or if shut down before lock acquired.
                    int rs = runStateOf(ctl.get());

                    //只有是RUNNING 或者 SHUTDOWN状态的来帮助处理任务的线程才允许创建
                    if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) {
                        // 如果线程已经被start过了，则抛出异常，不允许重复调用start
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        //添加到worker的set
                        workers.add(w);
                        int s = workers.size();
                        //???
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                //如果任务添加成功了，那么start线程，最后标记线程启动成功！
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

    /**
     * 回滚工作线程的创建。
     * 如果存在，则从 workers 中移除工作线程
     * 减少工作线程计数
     * 重新检查终止状态，以防此工作线程的存在阻止终止操作
     */
    private void addWorkerFailed(Worker w) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            if (w != null)
                workers.remove(w);
            //线程数-1
            decrementWorkerCount();
            tryTerminate();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 对于即将终止的工作线程执行清理和簿记工作。仅从工作线程中调用。除非设置了 completedAbruptly，
     * 否则假定 workerCount 已经调整以考虑退出。该方法从工作线程集中移除线程，并在以下情况下终止线程池或替换工作线程：
     * 工作线程由于用户任务异常而退出。
     * 运行的核心线程数少于 corePoolSize，或者队列非空但没有工作线程。
     * @param w the worker
     * @param completedAbruptly if the worker died due to user exception
     */
    private void processWorkerExit(Worker w, boolean completedAbruptly) {
        if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
            decrementWorkerCount();

        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks;
            workers.remove(w);
        } finally {
            mainLock.unlock();
        }

        tryTerminate();

        int c = ctl.get();
        // 如果当前线程池状态处于RUNNING、SHUTDOWN状态
        if (runStateLessThan(c, STOP)) {
            // 工作线程非异常
            if (!completedAbruptly) {
                // allowCoreThreadTimeOut这个值表示是否允许核心工作线程超时销毁
                // 如果允许，那么核心工作线程数最小为0
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
                // 如果最小保留的核心线程数为0并且任务队列不为空，表示至少还需要一个线程将任务完成
                if (min == 0 && ! workQueue.isEmpty())
                    min = 1;
                //线程足够跳出集合
                if (workerCountOf(c) >= min)
                    return; // replacement not needed
            }
            // 如果当前运行的Worker数比当前需要的Worker数少的话，会调用addWorker，添加新的Worker
            addWorker(null, false);
        }
    }

    /**
     * 根据当前的配置设置，执行阻塞或定时等待任务，或者如果满足以下任何条件时返回 null，表示该工作线程必须退出：
     * 存在超过 maximumPoolSize 的工作线程（由调用 setMaximumPoolSize 导致）。
     * 线程池已停止。
     * 线程池已关闭并且队列为空。
     * 此工作线程等待任务超时，并且超时的工作线程可以终止（即 allowCoreThreadTimeOut 为 true 或 workerCount > corePoolSize），
     * 无论是在定时等待之前还是之后，如果队列非空且此工作线程不是池中的最后一个线程。
     * 返回任务，如果工作线程必须退出，则返回 null，并减少 workerCount。
     */
    private Runnable getTask() {
        //上次的poll()是否超时？
        boolean timedOut = false; // Did the last poll() time out?

        for (;;) {
            int c = ctl.get();
            //线程池的状态
            int rs = runStateOf(c);

            // 线程池SHUTDOWN了，并且队列中没有任务了 或者 大于等于STOP即便队列中有任务也不会去处理了
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            //worker 数量
            int wc = workerCountOf(c);

            // 核心线程池也可以被淘汰
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            //我们可以在线程运行时动态调整线程池中的线程数量  所以wc>maximumPoolSize可能回存在
            if ((wc > maximumPoolSize || (timed && timedOut)) && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            try {
                Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

    /**
     * 主要的工作线程运行循环。重复从队列中获取任务并执行它们，同时处理以下几个问题：
     * 我们可能会从初始任务开始，这种情况下我们不需要获取第一个任务。否则，只要线程池正在运行，我们就从 getTask 获取任务。
     * 如果 getTask 返回 null，那么工作线程将因为线程池状态或配置参数的改变而退出。
     * 其他退出情况是由外部代码中的异常抛出引起的，这种情况下 completedAbruptly 为 true，通常会导致 processWorkerExit 方法替换该线程。
     *
     * 在运行任何任务之前，会获取锁以防止任务执行时发生其他线程池中断，并确保除非线程池正在停止，否则该线程没有中断标记。
     *
     * 在每个任务运行之前，会调用 beforeExecute 方法，它可能会抛出异常，如果是这种情况，我们会导致线程终止（通过将 completedAbruptly 设置为 true），而不处理该任务。
     *
     * 假设 beforeExecute 方法正常完成，我们运行任务，并收集任何抛出的异常以发送给 afterExecute 方法。
     * 我们分别处理 RuntimeException、Error（规范保证我们会捕获这两种异常）和任意的 Throwable。由于我们不能在 Runnable.run 中重新抛出 Throwable，
     * 因此我们在返回时将它们包装在 Errors 中（发送给线程的 UncaughtExceptionHandler）。任何抛出的异常也会导致线程终止。
     *
     * 在 task.run 完成后，我们调用 afterExecute 方法，该方法也可能抛出异常，这也会导致线程终止。根据 JLS 第 14.20 节的规定，此异常将是有效的，即使 task.run 抛出了异常。
     *
     * 异常处理机制的净效果是，afterExecute 方法和线程的 UncaughtExceptionHandler 将获得我们可以提供的关于用户代码遇到的任何问题的准确信息。
     * @param w the worker
     */
    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        //取消引用
        w.firstTask = null;
        /*
         * 这里不是解锁操作，这里是为了设置state = 0 以及 ExclusiveOwnerThread = null，因为起始状态state = -1, 不允许任何线程抢占锁，
         * 这里就是初始化操作。
         */
        w.unlock(); // allow interrupts 允许中断
        //是否因为异常跳出
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                /*
                 * 加锁 设置独占锁为当前线程 防止其他线程将当前线程中断
                 * 为什么要设置独占锁？shutdown时会判断当前worker状态，根据独占锁是否空闲来判断当前worker是否正在工作
                 */
                w.lock();
                // 如果线程池正在停止，确保线程被中断；
                //如果不是，则确保线程没有被中断。对于第二种情况，需要重新检查来处理在清除中断时的 shutdownNow 竞争情况。
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    //子类可以继承后重写该方法
                    beforeExecute(wt, task);
                    //记录下异常
                    Throwable thrown = null;
                    try {
                        //执行任务
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        //子类可以继承后重写该方法
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    //无论正常执行完毕还是异常执行完毕都会++
                    w.completedTasks++;
                    w.unlock();
                }
            }
            /*
             * 什么情况下，会来到这里？
             * 当getTask()返回null时，说明当前线程应该退出了
             * 退出的原因
             * 1.该线程超过了超时时间
             * 2.线程池shutdown了且任务队列中没有任务了
             * 3.线城市大于等于STOP状态了（即便队列中有任务也不处理了）
             */
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

    // Public constructors and methods

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory and rejected execution handler.
     * It may be more convenient to use one of the {@link Executors} factory
     * methods instead of this general purpose constructor.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default rejected execution handler.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        //核心线程数量可以为0
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

    /**
     * 在将来的某个时刻执行给定的任务。任务可以在新线程中执行，也可以在现有的线程池线程中执行,也可能由调用线程执行。
     *
     * 如果无法将任务提交执行，可能是因为该执行器已被关闭或者其容量已满，那么该任务将由当前的RejectedExecutionHandler处理。
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         * 如果正在运行的线程数少于核心线程池大小（corePoolSize），则尝试使用给定的命令作为其第一个任务启动一个新线程。
         * 调用addWorker方法会原子地检查运行状态（runState）和工作线程计数（workerCount），因此通过返回false可以防止错误报警，避免在不应添加线程的情况下添加线程。
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         * 如果任务可以成功排队，我们仍然需要双重检查是否应该添加一个线程（因为上次检查以来现有线程已经终止），或者线程池在进入此方法后关闭。
         * 因此，我们重新检查状态，并根据需要回滚排队操作（如果已停止），或者如果没有线程，则启动一个新线程。
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         * 如果无法将任务排队，那么我们尝试添加一个新线程。如果添加失败，我们知道线程池已关闭或达到饱和状态，因此拒绝该任务。
         */
        int c = ctl.get();
        //如果现有线程数小于核心线程数
        if (workerCountOf(c) < corePoolSize) {
            //尝试增加worker处理当前任务
            if (addWorker(command, true))
                return;
            //增加worker失败（失败的原因可能是并发执行增加worker时该线程失败了，也可能是线程池正在关闭），重新获取线程池状态
            c = ctl.get();
        }
        //将任务添加至阻塞队列
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            //添加到队列之后发现线程池停止工作了则从队列中移除刚刚添加的任务，并执行拒绝策略
            if (! isRunning(recheck) && remove(command))
                reject(command);
            //线程池还在运行中或者线程池处于shutdown状态，但是队列中还有任务，但是线程池中没有线程了（可能是线程发生了异常），增加一个线程来处理任务
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        //如果线程池停止运行了或者添加到阻塞队列失败了则尝试创建非核心线程（创建非核心线程的时候也会判断线程池的状态）
        else if (!addWorker(command, false))
            //创建非核心线程失败则触发拒绝策略
            reject(command);
    }

    /**
     *启动有序关闭，之前提交的任务将被执行，但不会接受新任务。如果已经关闭，调用此方法不会产生额外的效果。
     *该方法不会等待之前提交的任务完成执行。如果需要等待任务完成，可以使用 awaitTermination 方法。
     *
     * @throws SecurityException {@inheritDoc}
     */
    public void shutdown() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(SHUTDOWN);
            interruptIdleWorkers();
            onShutdown(); // hook for ScheduledThreadPoolExecutor
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
    }

    /**
     * 尝试停止所有正在执行的任务，停止处理等待中的任务，并返回一个等待执行的任务列表。这些任务在方法返回时从任务队列中移除。
     *
     * 该方法不会等待正在执行的任务终止。如果需要等待任务完成，可以使用 awaitTermination 方法。
     *
     * 无法保证完全停止正在执行的任务，只能尽力尝试。此实现通过使用 Thread#interrupt 方法取消任务，因此任何无法响应中断的任务可能永远无法终止。
     *
     * @throws SecurityException {@inheritDoc}
     */
    public List<Runnable> shutdownNow() {
        List<Runnable> tasks;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(STOP);
            interruptWorkers();
            tasks = drainQueue();
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
        return tasks;
    }

    public boolean isShutdown() {
        return ! isRunning(ctl.get());
    }

    /**
     * 如果执行器正在经历 shutdown 或 shutdownNow 过程中但尚未完全终止，则返回 true。
     * 此方法在调试过程中可能很有用。如果在 shutdown 后的足够长时间内返回 true，可能表明提交的任务已忽略或抑制中断，导致执行器无法正确终止。
     *
     * @return {@code true} if terminating but not yet terminated
     */
    public boolean isTerminating() {
        int c = ctl.get();
        return ! isRunning(c) && runStateLessThan(c, TERMINATED);
    }

    public boolean isTerminated() {
        return runStateAtLeast(ctl.get(), TERMINATED);
    }

    public boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (;;) {
                if (runStateAtLeast(ctl.get(), TERMINATED))
                    return true;
                if (nanos <= 0)
                    return false;
                nanos = termination.awaitNanos(nanos);
            }
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 在此执行器不再被引用且没有线程时，调用 shutdown 方法。
     */
    protected void finalize() {
        SecurityManager sm = System.getSecurityManager();
        if (sm == null || acc == null) {
            shutdown();
        } else {
            PrivilegedAction<Void> pa = () -> { shutdown(); return null; };
            AccessController.doPrivileged(pa, acc);
        }
    }

    /**
     * Sets the thread factory used to create new threads.
     *
     * @param threadFactory the new thread factory
     * @throws NullPointerException if threadFactory is null
     * @see #getThreadFactory
     */
    public void setThreadFactory(ThreadFactory threadFactory) {
        if (threadFactory == null)
            throw new NullPointerException();
        this.threadFactory = threadFactory;
    }

    /**
     * Returns the thread factory used to create new threads.
     *
     * @return the current thread factory
     * @see #setThreadFactory(ThreadFactory)
     */
    public ThreadFactory getThreadFactory() {
        return threadFactory;
    }

    /**
     * Sets a new handler for unexecutable tasks.
     *
     * @param handler the new handler
     * @throws NullPointerException if handler is null
     * @see #getRejectedExecutionHandler
     */
    public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
        if (handler == null)
            throw new NullPointerException();
        this.handler = handler;
    }

    /**
     * Returns the current handler for unexecutable tasks.
     *
     * @return the current handler
     * @see #setRejectedExecutionHandler(RejectedExecutionHandler)
     */
    public RejectedExecutionHandler getRejectedExecutionHandler() {
        return handler;
    }

    /**
     * 设置核心线程数。这会覆盖构造函数中设置的任何值。如果新值小于当前值，则多余的现有线程将在下次空闲时被终止。如果新值较大，将会在需要时启动新线程来执行任何排队的任务。
     *
     * @param corePoolSize the new core size
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     * @see #getCorePoolSize
     */
    public void setCorePoolSize(int corePoolSize) {
        if (corePoolSize < 0)
            throw new IllegalArgumentException();
        int delta = corePoolSize - this.corePoolSize;
        this.corePoolSize = corePoolSize;
        if (workerCountOf(ctl.get()) > corePoolSize)
            interruptIdleWorkers();
        else if (delta > 0) {
            // 我们实际上不知道需要多少新线程。
            // 作为一种启发式方法，预启动足够多的新工作线程（最多为新的核心大小），以处理队列中当前的任务数量，但如果在此过程中队列变为空，则停止预启动。
            int k = Math.min(delta, workQueue.size());
            while (k-- > 0 && addWorker(null, true)) {
                if (workQueue.isEmpty())
                    break;
            }
        }
    }

    /**
     * Returns the core number of threads.
     *
     * @return the core number of threads
     * @see #setCorePoolSize
     */
    public int getCorePoolSize() {
        return corePoolSize;
    }

    /**
     * 启动一个核心线程，使其处于等待工作的空闲状态。这会覆盖仅在执行新任务时才启动核心线程的默认策略。如果所有核心线程已经启动，则此方法将返回 false。
     *
     * @return {@code true} if a thread was started
     */
    public boolean prestartCoreThread() {
        return workerCountOf(ctl.get()) < corePoolSize &&
            addWorker(null, true);
    }

    /**
     * 与 prestartCoreThread 相同，只是即使 corePoolSize 为0，也会确保至少启动一个线程。
     */
    void ensurePrestart() {
        int wc = workerCountOf(ctl.get());
        if (wc < corePoolSize)
            addWorker(null, true);
        else if (wc == 0)
            addWorker(null, false);
    }

    /**
     * 启动所有核心线程，使它们空闲等待工作。这将覆盖仅在执行新任务时才启动核心线程的默认策略。
     *
     * @return the number of threads started
     */
    public int prestartAllCoreThreads() {
        int n = 0;
        while (addWorker(null, true))
            ++n;
        return n;
    }

    /**
     * 如果此线程池允许核心线程在没有任务到达时根据 keepAlive 时间进行超时和终止，并在新任务到达时进行替换，则返回 true。
     * 当为 true 时，非核心线程适用的相同保持活动策略也适用于核心线程。当为 false（默认值）时，核心线程不会因为缺少入站任务而终止。
     *
     * @return {@code true} if core threads are allowed to time out,
     *         else {@code false}
     *
     * @since 1.6
     */
    public boolean allowsCoreThreadTimeOut() {
        return allowCoreThreadTimeOut;
    }

    /**
     * 设置核心线程是否可以根据 keep-alive 时间超时并终止，以及在新任务到达时进行替换（如果需要）的策略。
     * 当设置为 false 时，核心线程不会因为缺少入站任务而终止。当设置为 true 时，非核心线程适用的相同保持活动策略也适用于核心线程。
     * 为了避免频繁的线程替换，当设置为 true 时，保持活动时间必须大于零。通常在使用线程池之前调用此方法。
     *
     * @param value {@code true} if should time out, else {@code false}
     * @throws IllegalArgumentException if value is {@code true}
     *         and the current keep-alive time is not greater than zero
     *
     * @since 1.6
     */
    public void allowCoreThreadTimeOut(boolean value) {
        if (value && keepAliveTime <= 0)
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
        if (value != allowCoreThreadTimeOut) {
            allowCoreThreadTimeOut = value;
            if (value)
                interruptIdleWorkers();
        }
    }

    /**
     * Sets the maximum allowed number of threads. This overrides any
     * value set in the constructor. If the new value is smaller than
     * the current value, excess existing threads will be
     * terminated when they next become idle.
     *
     * @param maximumPoolSize the new maximum
     * @throws IllegalArgumentException if the new maximum is
     *         less than or equal to zero, or
     *         less than the {@linkplain #getCorePoolSize core pool size}
     * @see #getMaximumPoolSize
     */
    public void setMaximumPoolSize(int maximumPoolSize) {
        if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
            throw new IllegalArgumentException();
        this.maximumPoolSize = maximumPoolSize;
        if (workerCountOf(ctl.get()) > maximumPoolSize)
            interruptIdleWorkers();
    }

    /**
     * Returns the maximum allowed number of threads.
     *
     * @return the maximum allowed number of threads
     * @see #setMaximumPoolSize
     */
    public int getMaximumPoolSize() {
        return maximumPoolSize;
    }

    /**
     * Sets the time limit for which threads may remain idle before
     * being terminated.  If there are more than the core number of
     * threads currently in the pool, after waiting this amount of
     * time without processing a task, excess threads will be
     * terminated.  This overrides any value set in the constructor.
     *
     * @param time the time to wait.  A time value of zero will cause
     *        excess threads to terminate immediately after executing tasks.
     * @param unit the time unit of the {@code time} argument
     * @throws IllegalArgumentException if {@code time} less than zero or
     *         if {@code time} is zero and {@code allowsCoreThreadTimeOut}
     * @see #getKeepAliveTime(TimeUnit)
     */
    public void setKeepAliveTime(long time, TimeUnit unit) {
        if (time < 0)
            throw new IllegalArgumentException();
        if (time == 0 && allowsCoreThreadTimeOut())
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
        long keepAliveTime = unit.toNanos(time);
        long delta = keepAliveTime - this.keepAliveTime;
        this.keepAliveTime = keepAliveTime;
        if (delta < 0)
            interruptIdleWorkers();
    }

    /**
     * Returns the thread keep-alive time, which is the amount of time
     * that threads in excess of the core pool size may remain
     * idle before being terminated.
     *
     * @param unit the desired time unit of the result
     * @return the time limit
     * @see #setKeepAliveTime(long, TimeUnit)
     */
    public long getKeepAliveTime(TimeUnit unit) {
        return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
    }

    /* User-level queue utilities */

    /**
     * Returns the task queue used by this executor. Access to the
     * task queue is intended primarily for debugging and monitoring.
     * This queue may be in active use.  Retrieving the task queue
     * does not prevent queued tasks from executing.
     *
     * @return the task queue
     */
    public BlockingQueue<Runnable> getQueue() {
        return workQueue;
    }

    /**
     * Removes this task from the executor's internal queue if it is
     * present, thus causing it not to be run if it has not already
     * started.
     *
     * <p>This method may be useful as one part of a cancellation
     * scheme.  It may fail to remove tasks that have been converted
     * into other forms before being placed on the internal queue. For
     * example, a task entered using {@code submit} might be
     * converted into a form that maintains {@code Future} status.
     * However, in such cases, method {@link #purge} may be used to
     * remove those Futures that have been cancelled.
     *
     * @param task the task to remove
     * @return {@code true} if the task was removed
     */
    public boolean remove(Runnable task) {
        boolean removed = workQueue.remove(task);
        tryTerminate(); // In case SHUTDOWN and now empty
        return removed;
    }

    /**
     * 尝试从工作队列中移除所有已取消的{@link Future}任务。
     * 该方法可以作为存储回收操作使用，对功能没有其他影响。已取消的任务永远不会被执行，但可能会在工作队列中累积，直到工作线程能够主动移除它们。
     * 调用此方法可以立即尝试移除它们。然而，在其他线程干扰的情况下，此方法可能无法成功移除任务。
     */
    public void purge() {
        final BlockingQueue<Runnable> q = workQueue;
        try {
            Iterator<Runnable> it = q.iterator();
            while (it.hasNext()) {
                Runnable r = it.next();
                if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
                    it.remove();
            }
        } catch (ConcurrentModificationException fallThrough) {
            // Take slow path if we encounter interference during traversal.
            // Make copy for traversal and call remove for cancelled entries.
            // The slow path is more likely to be O(N*N).
            for (Object r : q.toArray())
                if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
                    q.remove(r);
        }

        tryTerminate(); // In case SHUTDOWN and now empty
    }

    /* Statistics */

    /**
     * Returns the current number of threads in the pool.
     *
     * @return the number of threads
     */
    public int getPoolSize() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            // Remove rare and surprising possibility of
            // isTerminated() && getPoolSize() > 0
            return runStateAtLeast(ctl.get(), TIDYING) ? 0
                : workers.size();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 返回当前正在执行任务的线程的近似数量。
     *
     * @return the number of threads
     */
    public int getActiveCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            int n = 0;
            for (Worker w : workers)
                if (w.isLocked())
                    ++n;
            return n;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the largest number of threads that have ever
     * simultaneously been in the pool.
     *
     * @return the number of threads
     */
    public int getLargestPoolSize() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            return largestPoolSize;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 返回曾经被调度执行的任务的近似总数。由于任务和线程的状态在计算过程中可能会动态变化，返回的值只是一个近似值。
     *
     * @return the number of tasks
     */
    public long getTaskCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            long n = completedTaskCount;
            for (Worker w : workers) {
                n += w.completedTasks;
                if (w.isLocked())
                    ++n;
            }
            return n + workQueue.size();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * 返回已完成执行的任务的近似总数。由于任务和线程的状态在计算过程中可能会动态变化，返回的值只是一个近似值，但在连续调用中不会减少。
     *
     * @return the number of tasks
     */
    public long getCompletedTaskCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            long n = completedTaskCount;
            for (Worker w : workers)
                n += w.completedTasks;
            return n;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns a string identifying this pool, as well as its state,
     * including indications of run state and estimated worker and
     * task counts.
     *
     * @return a string identifying this pool, as well as its state
     */
    public String toString() {
        long ncompleted;
        int nworkers, nactive;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            ncompleted = completedTaskCount;
            nactive = 0;
            nworkers = workers.size();
            for (Worker w : workers) {
                ncompleted += w.completedTasks;
                if (w.isLocked())
                    ++nactive;
            }
        } finally {
            mainLock.unlock();
        }
        int c = ctl.get();
        String rs = (runStateLessThan(c, SHUTDOWN) ? "Running" :
                     (runStateAtLeast(c, TERMINATED) ? "Terminated" :
                      "Shutting down"));
        return super.toString() +
            "[" + rs +
            ", pool size = " + nworkers +
            ", active threads = " + nactive +
            ", queued tasks = " + workQueue.size() +
            ", completed tasks = " + ncompleted +
            "]";
    }

    /* Extension hooks */

    /**
     * 在给定线程中执行给定的Runnable之前调用的方法。此方法由将执行任务的线程t调用，可以用于重新初始化ThreadLocals或执行日志记录。
     *
     * 此实现不执行任何操作，但可以在子类中进行自定义。注意：为了正确嵌套多个覆盖，子类通常应在此方法的末尾调用super.beforeExecute。
     *
     * @param t the thread that will run task {@code r}
     * @param r the task that will be executed
     */
    protected void beforeExecute(Thread t, Runnable r) { }

    /**
     * 在完成执行给定的Runnable后调用的方法。此方法由执行任务的线程调用。如果非空，则Throwable是导致执行突然终止的未捕获的RuntimeException或Error。
     *
     * 此实现不执行任何操作，但可以在子类中进行自定义。注意：为了正确嵌套多个覆盖，子类通常应在此方法的开头调用super.afterExecute。
     *
     * 注意：当操作包含在任务中（例如FutureTask）中，无论是显式地还是通过submit等方法，这些任务对象都会捕获和维护计算异常，因此它们不会导致突然终止，
     * 并且内部异常不会传递给此方法。如果您想在此方法中捕获这两种故障，您可以进一步检测此类情况，例如在此示例子类中打印直接原因或底层异常（如果任务已中止）：
     *
     *  <pre> {@code
     * class ExtendedExecutor extends ThreadPoolExecutor {
     *   // ...
     *   protected void afterExecute(Runnable r, Throwable t) {
     *     super.afterExecute(r, t);
     *     if (t == null && r instanceof Future<?>) {
     *       try {
     *         Object result = ((Future<?>) r).get();
     *       } catch (CancellationException ce) {
     *           t = ce;
     *       } catch (ExecutionException ee) {
     *           t = ee.getCause();
     *       } catch (InterruptedException ie) {
     *           Thread.currentThread().interrupt(); // ignore/reset
     *       }
     *     }
     *     if (t != null)
     *       System.out.println(t);
     *   }
     * }}</pre>
     *
     * @param r the runnable that has completed
     * @param t the exception that caused termination, or null if
     * execution completed normally
     */
    protected void afterExecute(Runnable r, Throwable t) { }

    /**
     * 在线程池终止时调用的方法。默认实现不执行任何操作。
     * 注意：为了正确嵌套多个重写，子类通常应在此方法中调用 {@code super.terminated}。
     */
    protected void terminated() { }

    /* Predefined RejectedExecutionHandlers */

    /**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     * 调用线程执行
     */
    public static class CallerRunsPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() { }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

    /**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     * 抛出异常
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }

    /**
     * A handler for rejected tasks that silently discards the rejected task.
     * 无声抛弃
     */
    public static class DiscardPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public DiscardPolicy() { }

        /**
         * Does nothing, which has the effect of discarding task r.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }

    /**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     * 抛弃等待时间最久的
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public DiscardOldestPolicy() { }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                //队列头部的就是等待时间最久的
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }
}
